package com.dhcc.DRGsHosp.facade.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.inject.Named;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.openkoala.koala.commons.InvokeResult;
import org.openkoala.koalacommons.resourceloader.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.dhcc.DRGsHosp.application.OtherTargetApplication;
import com.dhcc.DRGsHosp.facade.OtherTargetFacade;
import com.dhcc.DRGsHosp.infra.util.MonitorResultUtil;


/**
 * @title		:OtherTargetFacadeImpl.java
 * @description	:医院其他指标业务实现层
 * @author		:yujiaolong
 * @date		:2017年5月25日
 * @version     :2.4
 */
@Named("otherTargetFacadeyjl170525")
public class OtherTargetFacadeImpl implements OtherTargetFacade{

	@Autowired
	OtherTargetApplication otherTargetApplication;
	
	@Override
	public InvokeResult analysisTarget(String filePath) {
		List<Map<String,String>> targetXmlList = getTargetXML();
		Integer listSize = targetXmlList.size();
		String extension = filePath.substring(filePath.lastIndexOf("."));// 扩展名
		List<Map<String, Object>> targetExcleList =new ArrayList <Map<String, Object>>();
		if (".xls".equals(extension) || ".xlsx".equals(extension)) {
			try {
				Workbook workbook = null;
				Sheet sheet = null;
				if (extension.equals(".xls")) {
					try {
						workbook = new HSSFWorkbook(new FileInputStream(filePath));
						int sheetn = workbook.getNumberOfSheets();
						for(int i=0; i<sheetn; i++){
							sheet = workbook.getSheetAt(i);
							List<Map<String, Object>> targetExcleList1 = orsSheet(sheet, targetXmlList);
							targetExcleList.addAll(targetExcleList1);
						}
					} catch (IOException e) {
						e.printStackTrace();
					}
				} else if (extension.equals(".xlsx")) {
					try {
						workbook = new XSSFWorkbook(new FileInputStream(filePath));
						int sheetn = workbook.getNumberOfSheets();
						for(int i=0; i<sheetn; i++){
							sheet = workbook.getSheetAt(i);
							List<Map<String, Object>> targetExcleList1 = orsSheet(sheet, targetXmlList);
							targetExcleList.addAll(targetExcleList1);
						}
					} catch (IOException e) {
						e.printStackTrace();
					}
				} else {
					System.err.println("上传的文件不是有效的excel文件！");
				}

				/**
				 * 读取完数据以后删除upload下的所有文件
				 */
				File tempFile = new File(filePath);
				File[] tempList = tempFile.listFiles();
				if (tempFile.isFile()) {
					tempFile.delete();
				} else {
					for (int i = 0; i < tempList.length; i++) {
						tempList[i].delete();
					}
				}
				
			} catch (Exception e) {
				e.printStackTrace();
				return InvokeResult.failure(""); 
			}
		}
		if(targetExcleList.size()<=0){
			return InvokeResult.failure("没有上传任何数据！");
		}else{
			for(Map<String, Object> map:targetExcleList){
				otherTargetApplication.insertTarget(map,listSize,MonitorResultUtil.object2String(map.get("code")));
			}
			return InvokeResult.success("文件上传成功");
		}
	}
	
	private Map<String, Object> orsSheetRows5h(Row row){
		Map<String, Object> map= new HashMap<String,Object>();
		//科室
		Cell cell = row.getCell(0);
		if (cell != null) {
			cell.setCellType(Cell.CELL_TYPE_STRING);
			map.put("code", cell.getStringCellValue());
		}
		//年份
		cell = row.getCell(1);
		if (cell != null) {
			cell.setCellType(Cell.CELL_TYPE_STRING);
			map.put("year", cell.getStringCellValue());
		}
		//月份
		cell = row.getCell(2);
		if (cell != null) {
			cell.setCellType(Cell.CELL_TYPE_STRING);
			map.put("month", cell.getStringCellValue());
		}
		//季度
		cell = row.getCell(3);
		if (cell != null) {
			cell.setCellType(Cell.CELL_TYPE_STRING);
			map.put("quarter", cell.getStringCellValue());
		}
		//备注
		cell = row.getCell(4);
		if (cell != null) {
			cell.setCellType(Cell.CELL_TYPE_STRING);
			map.put("remark", cell.getStringCellValue());
		}
		return map;
	}
	
	/**
	 * @methodname    :orsSheet1
	 * @description   :解析模板sheet1,sheet2
	 * @param         :
	 * @author        :lileizheng
	 * @param targetXmlList 
	 * @return        :
	 * @date          :2017年9月1日
	 */
	private List<Map<String, Object>> orsSheet(Sheet sheet, List<Map<String, String>> targetXmlList){
		List<Map<String, Object>> targetExcleList = new LinkedList<>();
		int rowCnt=sheet.getLastRowNum();//总行数
		//获取表头
		Row head = sheet.getRow(0);
		if(head==null) return new LinkedList<>();
		int cols = head.getLastCellNum();
		String[] headArr = new String[cols];
		for(int i=5; i<cols; i++){ //前5列固定值, 不需要读取配置
			Cell cell = head.getCell(i);
			if(cell==null) {
				headArr[i] = "";
			}else{
				headArr[i] = cell.getStringCellValue();
			}
		}
		// 循环每一行
		for (int j = 1; j<=rowCnt; j++) {
			Row row = sheet.getRow(j);
			Map<String, Object> map = orsSheetRows5h(row);
			if(map.get("month")!=null &&!"".equals(map.get("month"))){
				for(int i=5; i<cols; i=i+2){
					Cell cell = row.getCell(i);
					if (cell != null) {
						cell.setCellType(Cell.CELL_TYPE_STRING);
						for(Map<String, String> targetxml: targetXmlList){
							if(headArr[i].equals(targetxml.get("targetName"))){
								map.put(targetxml.get("targetCode"), cell.getStringCellValue());
								cell = row.getCell(i+1);
								if(cell!=null){
									cell.setCellType(Cell.CELL_TYPE_STRING);
									map.put(targetxml.get("targetCode")+"C", cell.getStringCellValue());
								}
								break;
							}
						}
					}
				}
			}else{
				for(int i=5; i<cols; i=i+1){
					Cell cell = row.getCell(i);
					if (cell != null) {
						cell.setCellType(Cell.CELL_TYPE_STRING);
						for(Map<String, String> targetxml: targetXmlList){
							if(headArr[i].equals(targetxml.get("targetName"))){
								map.put(targetxml.get("targetCode"), cell.getStringCellValue());
								break;
							}
						}
					}
				}
			}
			targetExcleList.add(map);
		}
		return targetExcleList;
	}
	
	/**
	 * @methodname :targetAdd
	 * @Description : 医院其他指标增加
	 * @author:yujiaolong
	 * @return InvokeResult
	 * @date :2017年5月29日
	 */
	@Override
	public InvokeResult targetAdd(Map<String,Object> dto){
		String targetType = MonitorResultUtil.object2String(dto.get("targetType"));
		String targetName = MonitorResultUtil.object2String(dto.get("targetName"));
		String targetCode = MonitorResultUtil.object2String(dto.get("targetCode"));
		SAXReader reader = new SAXReader();
		// 读取文件 转换成Document
		String xmlPath = OtherTargetFacadeImpl.class.getClassLoader()
				.getResource("").getPath()+ "config/hospOtherTarget/hospOtherTarget.xml";
		xmlPath = xmlPath.substring(1);
		Document document;
		try {
			document = reader.read(new File(xmlPath));
			Element root = document.getRootElement();
			Element element = root.element("documentHeader");
			Iterator<Element> iterator = element.elementIterator();
			while (iterator.hasNext()) {
				Element e = iterator.next();
				Attribute attribute_targetName = e.attribute("targetName");
				Attribute attribute_targetCode = e.attribute("targetCode");
				if (targetCode.equals(attribute_targetCode.getValue())) {
					return InvokeResult.failure("该指标代码已存在,清修改");
				}
				if (targetName.equals(attribute_targetName.getValue())) {
					return InvokeResult.failure("该指标名称已存在,清修改");
				}
			}
			try {
				Element e = element.addElement("target");
				e.addAttribute("targetCode", targetCode);
				e.addAttribute("targetName", targetName);
				e.addAttribute("targetType", targetType);
				saveDocument(document, new File(xmlPath));
			} catch (IOException e) {
				e.printStackTrace();
				return InvokeResult.failure(e.getMessage());
			}
			return InvokeResult.success();
		} catch (DocumentException e) {
			e.printStackTrace();
			return InvokeResult.failure(e.getMessage());
		}
	}
	
	/**
	 * @methodname :saveDocument
	 * @Description : xml重新生成
	 * @author:yujiaolong
	 * @return InvokeResult
	 * @date :2017年5月29日
	 */
	public void saveDocument(Document document,File xmlFile) throws IOException{
		Writer osWrite=new OutputStreamWriter(new FileOutputStream(xmlFile));//创建输出流  
		OutputFormat format = OutputFormat.createPrettyPrint();  //获取输出的指定格式    
		format.setEncoding("UTF-8");//设置编码 ，确保解析的xml为UTF-8格式  
		XMLWriter writer = new XMLWriter(osWrite,format);//XMLWriter 指定输出文件以及格式    
		writer.write(document);//把document写入xmlFile指定的文件(可以为被解析的文件或者新创建的文件)    
		writer.flush();  
		writer.close(); 
	}
    
	/**
	 * @methodname :getTargetXML
	 * @Description : 获取xml中的属性，并封装成list返回
	 * @author:yujiaolong
	 * @return InvokeResult
	 * @date :2017年5月29日
	 */
    public List<Map<String,String>> getTargetXML(){
    	List<Map<String,String>> listMap = new ArrayList<Map<String,String>>();
    	SAXReader reader = new SAXReader();  
		 //读取文件 转换成Document 
		String xmlPath = OtherTargetFacadeImpl.class.getClassLoader().getResource("").getPath()+"config/hospOtherTarget/hospOtherTarget.xml";
		System.out.println(xmlPath);
		xmlPath = xmlPath.substring(1);
        Document document;
        try {
			document = reader.read(new File(xmlPath));
			 Element root = document.getRootElement();  
			 Element element=root.element("documentHeader");
			 Iterator<Element> iterator = element.elementIterator();  
			 while(iterator.hasNext()){  
		            Element e = iterator.next();
		            Attribute attributeName=e.attribute("targetName");
		            if(!(attributeName.getValue()==null ||attributeName.getValue().trim()=="")){
		            	 Attribute attributeCode=e.attribute("targetCode");
		            	 Attribute attributeType=e.attribute("targetType");
		            	Map<String,String> map = new HashMap<String,String>();
		            	map.put("targetCode", attributeCode.getValue());
		            	map.put("targetName", attributeName.getValue());
		            	map.put("targetType", attributeType.getValue());
		            	listMap.add(map);
		            }
		            else{
		            	break;
		            }
		     }  
			 return listMap;
		} catch (DocumentException e) {
			e.printStackTrace();
		}
    	return null;
    }
    
    @Override
	public List<Map<String,Object>> depList(){
    	List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
    	List<Object[]> list=otherTargetApplication.depList();
    	if(list.size()>0){
    		for(Object[] obj:list){
    			Map<String, Object> map = new HashMap<>();
    			map.put("ddesc",obj[0]);
				map.put("ccode", obj[1]);
				resultList.add(map);
    		}
    		//return resultList;
    	}
    	return resultList;
    	
    }
    
    /**
   	 * @methodname :targetSelect
   	 * @Description : 根据指标类型查询这个类型下的所有指标
   	 * @author:yujiaolong
   	 * @return InvokeResult
   	 * @date :2017年5月29日
   	 */
	@Override
	public InvokeResult targetSelect(String targetType) {
		Map<String, Object> targetMap = new HashMap<>();
    	SAXReader reader = new SAXReader();  
		 //读取文件 转换成Document 
		String xmlPath = OtherTargetFacadeImpl.class.getClassLoader().getResource("").getPath()+"config/hospOtherTarget/hospOtherTarget.xml";
		xmlPath = xmlPath.substring(1);
        Document document;
        try {
			document = reader.read(new File(xmlPath));
			 Element root = document.getRootElement();  
			 Element element=root.element("documentHeader");
			 Iterator<Element> iterator = element.elementIterator();  
			 while(iterator.hasNext()){  
		            Element e = iterator.next();
		            Attribute attributeType=e.attribute("targetType");
		            if(attributeType!=null && StringUtils.hasLength(attributeType.getValue())){
		            	String atValue = attributeType.getValue();
		            	if(StringUtils.hasLength(targetType) && !atValue.contains(targetType)) continue;
		            	Attribute attributeCode=e.attribute("targetCode");
		            	Attribute attributeName=e.attribute("targetName");
            			Map<String,String> map = new HashMap<String,String>();
		            	map.put("targetCode", attributeCode.getValue());
		            	map.put("targetName", attributeName.getValue());
		            	map.put("targetType", attributeType.getValue());
		            	String[] atValues = atValue.split(",");
		            	//此处使用半递归方式,进行一次循环,按照指标分类进行获取
		            	for(String at: atValues){
		            		if(targetMap.containsKey(at)){
		            			List<Map<String, String>> l = (List) targetMap.get(at);
				            	l.add(map);
		            		}else{
		            			List<Map<String, String>> l = new LinkedList<>();
				            	l.add(map);
				            	targetMap.put(at, l);
		            		}
		            	}
		            }else{
		            	if(StringUtils.hasLength(targetType)) continue;
		            	Attribute attributeCode=e.attribute("targetCode");
		            	Attribute attributeName=e.attribute("targetName");
		            	Map<String,String> map = new HashMap<String,String>();
		            	map.put("targetCode", attributeCode.getValue());
		            	map.put("targetName", attributeName.getValue());
		            	map.put("targetType", attributeType.getValue());
		            	if(targetMap.containsKey("noTargetType")){
		            		List<Map<String, String>> l = (List<Map<String, String>>) targetMap.get("noTargetType");
			            	l.add(map);
		            	}else{
		            		List<Map<String, String>> l = new LinkedList<Map<String,String>>();
		            		l.add(map);
		            		targetMap.put("noTargetType", l);
		            	}
		            }
		     }  
			 return InvokeResult.success(targetMap);
		} catch (DocumentException e) {
			e.printStackTrace();
		}
    	return null;
	}
	
	/**
	 * @methodname :targetName
	 * @Description : 根根据指标代码查询指标名称
	 * @author:yujiaolong
	 * @return InvokeResult
	 * @date :2017年5月29日
	 */
	public String targetName(String targetCode) {
    	SAXReader reader = new SAXReader();  
		 //读取文件 转换成Document 
		String xmlPath = OtherTargetFacadeImpl.class.getClassLoader().getResource("").getPath()+"config/hospOtherTarget/hospOtherTarget.xml";
		System.out.println(xmlPath);
		xmlPath = xmlPath.substring(1);
        Document document;
        try {
			document = reader.read(new File(xmlPath));
			 Element root = document.getRootElement();  
			 Element element=root.element("documentHeader");
			 Iterator<Element> iterator = element.elementIterator();  
			 while(iterator.hasNext()){  
		            Element e = iterator.next();
		            Attribute attributeCode=e.attribute("targetCode");
		            if(attributeCode.getValue().equals(targetCode)){
		            	Attribute attributeName=e.attribute("targetName");
		            	return attributeName.getValue();
		            }
		     }  
			
		} catch (DocumentException e) {
			e.printStackTrace();
		}
    	return null;
	}

	public String ShowPercent(String targetCode) {
    	SAXReader reader = new SAXReader();  
		 //读取文件 转换成Document 
		String xmlPath = OtherTargetFacadeImpl.class.getClassLoader().getResource("").getPath()+"config/hospOtherTarget/hospOtherTarget.xml";
		System.out.println(xmlPath);
		xmlPath = xmlPath.substring(1);
        Document document;
        try {
			document = reader.read(new File(xmlPath));
			 Element root = document.getRootElement();  
			 Element element=root.element("documentHeader");
			 Iterator<Element> iterator = element.elementIterator();  
			 while(iterator.hasNext()){  
		            Element e = iterator.next();
		            Attribute attributeCode=e.attribute("targetCode");
		            if(attributeCode.getValue().equals(targetCode)){
		            	Attribute attributeName=e.attribute("ShowPercent");
		            	String flag=attributeName==null?"0":attributeName.getValue();
		            	if(!flag.equals("1")){
		            		flag="0";
		            	}
		            	return flag;
		            }
		     }  
			
		} catch (DocumentException e) {
			e.printStackTrace();
		}
    	return null;
	}
	/**
	 * @methodname :findTargetTable
	 * @Description : 医院指标数据查询
	 * @author:yujiaolong
	 * @return InvokeResult
	 * @date :2017年6月1日
	 */
	@Override
	public InvokeResult findTargetTable(Map dto) {
		List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
		DecimalFormat df= new DecimalFormat("##.##");//保留两位小数
		String [] monthArr= dto.get("month").toString().split(",");
		Integer size = monthArr.length;
		List<Object[]> list  = otherTargetApplication.findTargetTable(dto);
		String targetType = dto.get("targetType").toString();
		if(targetType.equals("drgs")){
			for(Object[] obj:list){
				Map<String, Object> map = new HashMap<>();
				if(obj[0].toString().equals("CMI")){
					map.put("targetName", "CMI值");
				}
				else if(obj[0].toString().equals("WEIGHT")){
					map.put("targetName", "人均总权重");
				}
				else if(obj[0].toString().equals("RATIO")){
					map.put("targetName", "中低风险死亡率");
				}
				else if(obj[0].toString().equals("RATE")){
					map.put("targetName", "低风险组死亡率");
				}
				else if(obj[0].toString().equals("FEE")){
					map.put("targetName", "费用消耗指数");
				}
				else if(obj[0].toString().equals("TIME")){
					map.put("targetName", "时间消耗指数");
				}
				else if(obj[0].toString().equals("HIGHLEVLEOPER")){
					map.put("targetName", "高风险操作占比");
				}
				else if(obj[0].toString().equals("THORFORATIO")){
					map.put("targetName", "III、IV级手术占比");
				}
				else if(obj[0].toString().equals("AVGDASRIGHT")){
					map.put("targetName", "平均住院日达标率（与医院标准增减幅）");
				}
				
				map.put("depName", obj[1].toString());
				for(int i=2;i<size+2;i++){
					map.put("month"+monthArr[i-2], obj[i]);
				}
				resultList.add(map);
			}
		}
		else{
			for(Object[] obj:list){
				Map<String, Object> map = new HashMap<>();
				map.put("targetName", targetName(obj[0]==null?"":obj[0].toString()));
				map.put("depName", obj[1].toString());
				if (ShowPercent(obj[0] == null ? "" : obj[0].toString()).equals("1")) {
					for (int i = 2; i < size*2 + 2; i=i+2) {
						String b = "";
						if (obj[i] != null) {

							b = df.format(Double.valueOf(obj[i].toString()) * 100) + "%";
						}
						map.put("month" + monthArr[(i - 2)/2], b);
						map.put("month" + monthArr[(i - 2)/2]+"c", obj[i+1]);
					}
				}else{
					for(int i=2;i<size*2+2;i=i+2){
						map.put("month"+monthArr[(i-2)/2], obj[i]);
						map.put("month" + monthArr[(i - 2)/2]+"c", obj[i+1]);
					}
				}
				resultList.add(map);
			}
		}
		return InvokeResult.success(resultList);
	}

	
	
	/**
	 * @methodname :findQuarterTargetTable
	 * @Description : 医院指标数据查询
	 * @author:yujiaolong
	 * @return InvokeResult
	 * @date :2017年7月6日
	 */
	@Override
	public InvokeResult findQuarterTargetTable(Map dto) {
		List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
		String [] quanterArr= dto.get("quarter").toString().split(",");
		Integer size = quanterArr.length;
		String targetTypeCodes = dto.get("targetTypeCodes").toString();
		String [] targetTypeArr= targetTypeCodes.split(","); 
		List<Object[]> list  = otherTargetApplication.findQuarterTargetTable(dto);
		String targetType = dto.get("targetType").toString();
			for(Object[] obj:list){
				Map<String, Object> map = new HashMap<>();
				int j=4;
				map.put("year", obj[0]);
				map.put("quarter", obj[1]);
				map.put("depName", obj[2]);
				map.put("remark", obj[3]);
				for(int i=0;i<targetTypeArr.length;i++){
					map.put(targetName(targetTypeArr[i]),obj[j]);
					j++;
				}
				
				resultList.add(map);
			}
		return InvokeResult.success(resultList);
	}
	
}
